package org.wotou.authority.service;

import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;
import org.wotou.authority.dao.ScheduleJobDAO;
import org.wotou.authority.domain.scheduleJobDO;
import org.wotou.authority.system.quartz.QuartzManager;

import java.util.List;

/**
 * spring初始化完毕后执行，启动监听器
 *
 * @author zhangQ
 * @date 2017/11/22
 */
@Service
public class StartUpPostProcessor implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;

    @Autowired
    private ScheduleJobDAO scheduleJobDAO;

    @Autowired
    private QuartzManager quartzManager;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        /*
        * 存在双容器情况下
        * 一个是root application context ,另一个就是我们自己的 projectName-servlet context（作为root application context的子容器）。
        * 这种情况下，就会造成onApplicationEvent方法被执行两次。
        * 为了避免上面提到的问题，在最后一次容器加载完成后执行逻辑（只适用双容器）
        * */
        if (null != contextRefreshedEvent.getApplicationContext().getParent()) {
            try {
                this.loderScheduler();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 加载定时任务
     */
    private void loderScheduler() throws Exception {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();

        // 从数据库中获取任务信息数据
//        List<scheduleJobDO> jobList = new ArrayList<scheduleJobDO>();
        List<scheduleJobDO> jobList = scheduleJobDAO.findAll();
/*        scheduleJobDO testJob = new scheduleJobDO();

        testJob.setJobName("任务名称1");
        testJob.setCronExpression("0/5 * * * * ?");
        testJob.setJobGroup("ssssss");
        testJob.setJobStatus(scheduleJobDO.STATUS_ENABLE);
        testJob.setSpringId("HtadminService");
        testJob.setMethodName("saveHtadminDO");
        testJob.setIsConcurrent(scheduleJobDO.CONCURRENT_IS);
        jobList.add(testJob);*/
        for (scheduleJobDO job : jobList) {
            quartzManager.addJob(job);
        }
    }
}
